# main.py
import base64
import datetime
import json
import os
import shutil
from time import sleep

from painter import TP, ProcessTimelinePlot


class FIFOPipeline:
    def __init__(self, fifo_path):
        self.fifo_path = fifo_path
        if not os.path.exists(fifo_path):
            os.mkfifo(fifo_path)
        self.plot = None

    def send_signal(self, signal):
        with open(self.fifo_path, "wb") as fifo:
            fifo.write(signal.encode())

    def read_data(self):
        with open(self.fifo_path, "rb") as fifo:
            data = fifo.read()
        data_str = data.decode().strip()[:-1]
        print(f"debug: {data_str}")
        data_list = json.loads(data_str)
        return [TP.from_dict(item) for item in data_list]

    def send_data(self, data):
        data_list = [item.to_dict() for item in data]
        data_str = json.dumps(data_list)
        with open(self.fifo_path, "wb") as fifo:
            fifo.write(data_str.encode())

    def run(self):
        pid = os.getpid()
        print(f"Hello! Printer PID: {pid}")

        data = self.read_data()
        if isinstance(data, list) and all(isinstance(item, TP) for item in data):
            self.plot = ProcessTimelinePlot(data)
            print("ready!")
        else:
            print(f"ERROR! Unexpected input: {data}")
            return

        if os.path.exists("output/"):
            shutil.rmtree("output/")

        os.mkdir("output/")

        self.plot.plot_full("output/")

        with open("output/finished.lock", "w") as lock_file:
            lock_file.write(str(datetime.datetime.now().timestamp()))

        print("Finished!")

        # while True:
        #     data = self.read_data()
        #     if isinstance(data, list) and all(isinstance(item, TP) for item in data):
        #         self.plot = ProcessTimelinePlot(data)
        #         self.send_signal("ready")
        #     elif data == "plot_full":
        #         image = self.plot.plot_full()
        #         encoded_image = base64.b64encode(image).decode()
        #         self.send_data(encoded_image)
        #     elif data == "plot_next_step":
        #         image = self.plot.step()
        #         encoded_image = base64.b64encode(image).decode()
        #         self.send_data(encoded_image)
        #     elif data == "exit":
        #         break


if __name__ == "__main__":
    fifo_path = "/tmp/my_fifo"
    pipeline = FIFOPipeline(fifo_path)
    pipeline.run()
